package com.persondemo.videoappliction.ui.publish;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.DyReleaseEntity;
import com.persondemo.videoappliction.bean.PutBean;
import com.persondemo.videoappliction.bean.UpimgBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.photo.PhotoPickerActivity;
import com.persondemo.videoappliction.photo.utils.ImageLoader;
import com.persondemo.videoappliction.ui.base.AppManager;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.publish.contract.PutContract;
import com.persondemo.videoappliction.ui.publish.presenter.PutPresenter;
import com.persondemo.videoappliction.utils.FalseClickListener;
import com.persondemo.videoappliction.utils.OtherUtils;
import com.persondemo.videoappliction.utils.PreferenceUtil;
import com.persondemo.videoappliction.utils.T;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Administrator on 2018/4/25.
 */

public class PutActivity extends BaseActivity<PutPresenter> implements PutContract.View {
    @BindView(R.id.put_back)
    ImageView putBack;
    @BindView(R.id.put_title)
    TextView putTitle;
    @BindView(R.id.put_text)
    TextView putText;
    @BindView(R.id.pub_edit_feed_input)
    EditText pubEditFeedInput;
    @BindView(R.id.pub_jianyi_tint)
    TextView pubJianyiTint;
    @BindView(R.id.releaseGridView)
    GridView releaseGridView;
    @BindView(R.id.addImg)
    ImageView addImg;
    @BindView(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    private int mColumnWidth;
    private GridAdapter mAdapter;
    private GridAdapter gridAdapter;
    private List<DyReleaseEntity> dyReleaseEntityList = new ArrayList<>();
    private List<String> mResults = new ArrayList<>();
    private String type = "";

    private String img = "";
   private String imei="";

    @Override
    public void onRetry() {
    }

    @Override
    public int getContentLayout() {
        return R.layout.module_activity_put;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void bindView(View view, Bundle savedInstanceState) {

    }

    @Override
    public void initData() {
        imei = PreferenceUtil.getString("imei", "");
        if (TextUtils.isEmpty(imei)) {
            T.showShort(PutActivity.this, "未获取到imei权限，请从设置打开授予权限！");
            return;
        }
        Intent intent = getIntent();
        if (intent != null) {
            type = intent.getStringExtra("type");
            if (type.equals("1")) {
                putTitle.setText("发表段子");
                relativeLayout.setVisibility(View.GONE);
            }else if (type.equals("2")){
                putTitle.setText("发表图片");
            }else {
                putTitle.setText("发表妹纸图");
            }
        }
        int screenWidth = OtherUtils.getWidthInPx(getApplicationContext());
        mColumnWidth = (screenWidth - OtherUtils.dip2px(getApplicationContext(), 4)) / 3;
        dyReleaseEntityList.clear();
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("1");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        gridAdapter = new GridAdapter(dyReleaseEntityList);
        releaseGridView.setAdapter(gridAdapter);
        gridAdapter.notifyDataSetChanged();
        pubEditFeedInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                pubJianyiTint.setText(s.length()+"/100");
                if (s.length()==0){
                    T.showShort(PutActivity.this,"最多输入100字！");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.put_back, R.id.put_text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.put_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.put_text:
                if (FalseClickListener.isFastDoubleClick()) {
                    T.showShort(PutActivity.this, "段子发表中，请勿重复点击");
                    return;
                } else {
                    updata();
                }
                break;
        }
    }

    private void updata() {
        String title = pubEditFeedInput.getText().toString();
        if (TextUtils.isEmpty(title)) {
            T.showShort(PutActivity.this, "发表内容不能为空！");
            return;
        }
        if (!type.equals("1")) {
            if (TextUtils.isEmpty(img)) {
                T.showShort(PutActivity.this, "请上传图片!");
                return;
            }
        }
        if (mPresenter != null) {
            showLoadingDialog();
               mPresenter.putdata(title,imei,img,type);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                showResult(result);
            }
        }
    }

    private void showResult(ArrayList<String> paths) {
        mResults.clear();
        dyReleaseEntityList.clear();
        gridAdapter.notifyDataSetChanged();
        for (int i = 0; i < paths.size(); i++) {
            DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
            dyReleaseEntity.setImgPath(paths.get(i));
            dyReleaseEntity.setImgType("1");
            dyReleaseEntityList.add(dyReleaseEntity);
            mResults.add(paths.get(i));
        }
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("2");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        if (mAdapter == null) {
            mAdapter = new GridAdapter(dyReleaseEntityList);
        }
        releaseGridView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        if (dyReleaseEntityList.size() > 8) {
            dyReleaseEntityList.remove(9);
        }
        yasuo(paths);

    }
private  void yasuo(ArrayList<String> photos){
    Luban.with(this)
            .load(photos)
            .ignoreBy(100)
            .setTargetDir(getPath())
            .setCompressListener(new OnCompressListener() {
                @Override
                public void onStart() {
                }

                @Override
                public void onSuccess(File file) {
                    Log.i("lidaming","11");
//                    filesList.add(file);
                    if (mPresenter != null) {
                            RequestBody requestFile =
                                    RequestBody.create(MediaType.parse("multipart/form-data"),file);
                            MultipartBody.Part body =
                                    MultipartBody.Part.createFormData("imgs",file.getName(), requestFile);
                            showLoadingDialog("图片上传中。。。");
                            mPresenter.upimgdata(body);
                        }

                }

                @Override
                public void onError(Throwable e) {
                }
            }).launch();
}
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }


    @Override
    public void imgdata(UpimgBean upimgBean) {
        hideLoadingDialog();
        if (upimgBean.getStatus() == 1) {
            if (TextUtils.isEmpty(img)){
                img = upimgBean.getData();
            }else {
                img = img + "," + upimgBean.getData();
            }
            T.showShort(PutActivity.this, upimgBean.getMsg());

        } else {
            T.showShort(PutActivity.this, upimgBean.getMsg()+"请重新上传图片！");
        }
    }

    @Override
    public void loadput(PutBean putBean) {
        hideLoadingDialog();
        if (putBean.getStatus()==1){
            T.showShort(PutActivity.this, putBean.getMsg());
            AppManager.getAppManager().finishActivity();
        }else {
            T.showShort(PutActivity.this, putBean.getMsg()+"请重新填写提交！");
        }
    }

    public class GridAdapter extends BaseAdapter {
        private List<DyReleaseEntity> pathList;

        public GridAdapter(List<DyReleaseEntity> pathList) {
            this.pathList = pathList;
        }

        @Override
        public int getCount() {
            return pathList.size();
        }

        @Override
        public Object getItem(int position) {
            return pathList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mColumnWidth*9/10, mColumnWidth);
                holder.imageView.setLayoutParams(params);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (pathList.get(position).getImgType().equals("2")) {
                holder.imageView.setBackgroundResource(R.drawable.ic_xiangji);
                holder.imageView.setEnabled(true);
                holder.imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PutActivity.this, PhotoPickerActivity.class);
                        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
                        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 3);
                        startActivityForResult(intent, 1);
                    }
                });
            } else {
                ImageLoader.getInstance().display(pathList.get(position).getImgPath(), holder.imageView, mColumnWidth, mColumnWidth);
                holder.imageView.setEnabled(false);
            }
            return convertView;
        }

        private class ViewHolder {
            public ImageView imageView;
        }
    }
}
